package com.woniu.controller;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.model.Container;
import com.woniu.entity.Result;
import com.woniu.pojo.TrainingInfo;
import com.woniu.service.ITrainingInfoService;
import com.woniu.util.DockerClientUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(tags = "docker环境启动")
@RestController
@RequestMapping("/docker")
public class DockerContorller extends BaseController{


    @Autowired
    private RedisTemplate redisTemplate;



    @Autowired
    private DockerClientUtils dockerClientUtils;

    @Autowired
    private ITrainingInfoService trainingInfoService;


    @ApiOperation("启动环境，创建docker容器")
    @GetMapping("/create/{trainingid}/{userid}")
    public Result  createDocker(@PathVariable Integer trainingid, @PathVariable Integer userid){
//        链接到docker
        DockerClient dockerClient = dockerClientUtils.connectDocker("tcp://192.168.232.121:2375");


//      查询该靶场id下，对应的容器名，和镜像名称
         TrainingInfo info = trainingInfoService.getTaraingById(trainingid);


        Container containerCmd = dockerClientUtils.getContainerCmd(dockerClient, "container_"+userid + info.getDocker());
//         判断容器是否存在
        if (containerCmd != null  ){
            //        设置对应redis的key,用来判断环境的使用时长
            redisTemplate.opsForValue().set("container_"+userid + info.getDocker(),1,3600,TimeUnit.SECONDS);
//       运行容器
            dockerClientUtils.startContainer(dockerClient,containerCmd.getId());
            // 拼接访问地址

            String url = "http://192.168.232.121:8081";
            String containersId = containerCmd.getId();
            Map<String, String> resultMap = new HashMap<>();
            resultMap.put("url", url);
            resultMap.put("containersId", containersId);
            return toDataResult(resultMap);
        }


//        创建docker容器

        CreateContainerResponse containers = dockerClientUtils.createContainers(dockerClient, "container_"+userid + info.getDocker(), "tomcat:8");

//        设置对应redis的key,用来判断环境的使用时长
        redisTemplate.opsForValue().set("container_"+userid + info.getDocker(), 1, 3600,TimeUnit.SECONDS);
//       运行容器
        dockerClientUtils.startContainer(dockerClient, containers.getId());
        // 拼接访问地址
        String url = "http://192.168.4.8:8081";
        String containersId = containers.getId();
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("url", url);
        resultMap.put("containersId", containersId);
        return toDataResult(resultMap);
    }

    @GetMapping("/delete/{containersid}/{userid}/{trainingid}")
    @ApiOperation("点击释放环境，删除容器,或者倒计时结束执行")
    public Result deleteDocker(@PathVariable String containersid,
                               @PathVariable Integer userid,
                               @PathVariable Integer trainingid) {
//        链接docker
        DockerClient dockerClient = dockerClientUtils.connectDocker("tcp://192.168.232.121:2375");
//         停止容器
        dockerClientUtils.stopContainer(dockerClient, containersid);
//         删除容器
        dockerClientUtils.removeContainer(dockerClient, containersid);

        //      查询该靶场id下，对应的容器名，和镜像名称
        TrainingInfo info = trainingInfoService.getTaraingById(trainingid);
//         获取对应的rediskey并删除
        String dockerkey = (String) redisTemplate.opsForValue().get("container_"+userid + info.getDocker());
        Boolean flag = redisTemplate.delete(dockerkey);
        return toDataResult(flag);
    }

    @GetMapping("/addtime/{userid}/{trainingid}")
    @ApiOperation("延长容器的测试时间")
    public Result addTime(@PathVariable Integer userid, @PathVariable Integer trainingid) {


//      查询该靶场id下，对应的容器名，和镜像名称
        TrainingInfo info = trainingInfoService.getTaraingById(trainingid);
//        获取rediskey的剩余时间
        Long expire = redisTemplate.opsForValue().getOperations().getExpire("container_"+userid + info.getDocker());
//        重新设置rediskey的过期时间,即容器的存在时间
        redisTemplate.opsForValue().set("container_"+userid + info.getDocker(), 1, expire + 1800,TimeUnit.SECONDS);
//         再次获取，确保时间已延长
        Long expirenext = redisTemplate.opsForValue().getOperations().getExpire("container_"+userid + info.getDocker());
        if (expirenext >= 1800) {

            return toDataResult(true);
        }
        return toDataResult(false);
    }

     @GetMapping("/expire/{userid}/{trainingid}")
     @ApiOperation("获取该时间的剩余时间")
     public Result expire(@PathVariable Integer userid, @PathVariable  Integer trainingid){

         //      查询该靶场id下，对应的容器名，和镜像名称
         TrainingInfo info = trainingInfoService.getTaraingById(trainingid);
//        获取rediskey的剩余时间
         Long expire = redisTemplate.opsForValue().getOperations().getExpire("container_"+userid + info.getDocker());

         return toDataResult(expire);
     }


}
